package com.clay.appointment.common.exception;

import com.clay.appointment.common.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 全局异常处理
 * </p>
 *
 * @author Yohann
 * @since 2020/9/21
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 通用异常拦截
     *
     * @param e 异常信息
     * @return ResponseBody
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        log.error("\nmessage:{}\ncause:{}", e.getMessage(), e.getCause(), e);

        return Result.error().message("未知错误：" + e.getMessage());
    }

    /**
     * 自定义异常拦截
     *
     * @param e 异常信息
     * @return ResponseBody
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public Result error(GlobalException e) {
        log.error("\nmessage:{}\ncause:{}", e.getMessage(), e.getCause(), e);

        return Result.error().code(e.getCode()).message(e.getMessage());
    }

    /**
     * 参数绑定异常拦截
     *
     * @param e 异常信息
     * @return ResponseBody
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result error(BindException e) {
        log.error("\nmessage:{}\ncause:{}", e.getMessage(), e.getCause(), e);

        return Result.error().code(ExceptionEnum.PARAMETER_ERROR.getCode()).message(e.getAllErrors().get(0).getDefaultMessage());
    }
}